package com.wangsai.framework.supersecurity.zuul;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.wangsai.framework.supersecurity.core.SuperSecurityManager;
import com.wangsai.framework.supersecurity.core.context.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import java.util.Optional;

/**
 * 代理拦截器
 *
 * @author Mr.Wang
 * @date 2021-08-02 10:25
 */
@RequiredArgsConstructor
public class SuperSecurityZuulFilter extends ZuulFilter {

    private final NotLoginZuulHandler notLoginZuulHandler;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        //1.获取上下文
        Optional<JSONObject> userOptional = UserContext.currentUserOfNullable();
        if (userOptional.isPresent()) {
            try {
                currentContext.addZuulRequestHeader(SuperSecurityManager.getConfig().getUserKey(),
                        SuperSecurityManager.getUserSecure().encode(userOptional.get().toJSONString()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        } else {
            notLoginZuulHandler.onNotLogin(currentContext);
        }
        //正常执行调用其他服务接口...
        return null;
    }
}